package com.winphone.uvam.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.winphone.uvam.common.BaseController;
import com.winphone.uvam.common.Constant;
import com.winphone.uvam.common.result.Result;
import com.winphone.uvam.entity.SysUser;
import com.winphone.uvam.service.ISysUserService;
import com.winphone.uvam.utils.ObjectUtils;
import com.winphone.uvam.utils.OperateImageUtils;
import com.winphone.uvam.utils.SessionUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lwl
 * @since 2017-12-13
 */
@Controller
@RequestMapping("/sysUser")
public class SysUserController extends BaseController {
    @Autowired
    ISysUserService iSysUserService;

    /**
     * windows 图片上传路径
     */
    @Value("${img.winLocation}")
    private String imgWinLocation;

    /**
     * liunx 临时图片上传路径
     */
    @Value("${img.linuxLocation}")
    private String imgLinuxLocation;

    /**
     * 分页查询
     * @param sysUser
     * @param current
     * @param size
     * @return
     */
    @RequestMapping(value = "/allParam",method = RequestMethod.POST)
    @ResponseBody
    public Object allParam(SysUser sysUser,
                           @RequestParam(value = "current",required = true) Integer current,
                           @RequestParam(value = "size",required = true) Integer size){
        Map<String, Object> condition = new HashMap<>();

        if (StringUtils.isNotEmpty(sysUser.getUsername())){
            condition.put("username",sysUser.getUsername());
        }

        if (StringUtils.isNotEmpty(sysUser.getTruename())){
            condition.put("truename",sysUser.getTruename());
        }
        Page<SysUser> pageInfo = iSysUserService.selectPageParam(new Page<SysUser>(current,size),condition);
        return pageInfo;

    }

    /**
     * 根据用户id查询用户信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/getSysUserInfoById",method = RequestMethod.POST)
    @ResponseBody
    public Object getSysUserInfoById(@RequestParam(value = "id") Long id){
        SysUser sysUser = iSysUserService.getSysUserInfoById(id);
        sysUser.setPassword(null);
        return renderSuccess(sysUser);
    }


    /**
     * 根据用户姓名查询用户信息
     * @param username
     * @return
     */
    @RequestMapping(value = "/getSysUserInfoByUserName",method = RequestMethod.POST)
    @ResponseBody
    public Object getSysUserInfoByUserName(@RequestParam(value = "username") String username){
        SysUser sysUser = iSysUserService.getSysUserInfoByUserName(username);
        sysUser.setPassword(null);
        return renderSuccess(sysUser);
    }

    /**
     * 新增  修改
     * @param sysUser
     * @return
     */
    @RequestMapping(value = {"/save","/update"},method = RequestMethod.POST)
    @ResponseBody
    public Object saveSysUser(@Valid SysUser sysUser,
                              @RequestParam(value = "file",required = false) MultipartFile file,
                              BindingResult result){
        // 参数校验
        if (result.hasErrors()){
            String resultMsg = result.getAllErrors().get(0).getDefaultMessage();
            return renderError(resultMsg, Result.OTHER);
        }
        StringBuilder fileNames = new StringBuilder();
        if(null != file && !file.isEmpty()){
            //保存文件并生成缩略图
            Result uploadResult = OperateImageUtils.saveImage(file,getImgSaveLocationPath());
            if(uploadResult.isSuccess()){
                //获得图片名并保存
                fileNames.append(uploadResult.getObj()).append(",");
            }else {
                return renderError(uploadResult.getMsg(),Result.OTHER);
            }
            //保存所有图片名参数
            if (fileNames.length() > 1){
                fileNames.deleteCharAt(fileNames.length()-1);
                sysUser.setTeacherImg(fileNames.toString());
            }
        }
        //新增
        if(sysUser.getId() == null){
            //用户名唯一性验证
            SysUser user = iSysUserService.getSysUserInfoByUserName(sysUser.getUsername());
            if(user != null){
                return renderError("用户名已存在",Result.OTHER);
            }
            sysUser.setCreateBy(SessionUtil.getCurrentUser().getId());
            sysUser.setCreateDate(new Date());
            sysUser.setIsDelete(Constant.DELETE_NO);
            //保存数据
            if (iSysUserService.insert(sysUser)){
                return renderSuccess();
            }else{
                return renderError();
            }
        }else{
            //修改
            sysUser.setUpdateBy(SessionUtil.getCurrentUser().getId());
            sysUser.setUpdateDate(new Date());
            //保存数据
            if (iSysUserService.updateSysUserInfo(sysUser)){
                return renderSuccess();
            }else{
                return renderError();
            }
        }
    }

    /**
     *  获取当前系统的图片上传路径，windows 和liunx 进行区分
     * @return
     */
    public String getImgSaveLocationPath(){
        if (currentOSName().startsWith("windows")){
            return imgWinLocation;
        } else{
            return imgLinuxLocation;
        }
    }

    /**
     * 获取当前操作系统
     * @return
     */
    private static String currentOSName(){
        String OS_NAME = System.getProperty("os.name").toLowerCase(Locale.US);
        return OS_NAME;
    }


    /**
     * 修改密码
     * @return
     */
    @RequestMapping(value = "/changePassword",method = RequestMethod.POST)
    @ResponseBody
    public Object changePassword(@RequestParam(value = "newPassword") String newPassword,
                                 @RequestParam(value = "phone") String phone){

        //参数验证
        if (StringUtils.isEmpty(newPassword)){
            return renderErrorParamNotNull();
        }
        //用户是否存在
        Long userId = SessionUtil.getCurrentUser().getId();
        //修改密码
        Result result = iSysUserService.updatePassword(userId,newPassword,phone);
        return result;
    }


    /**
     * 用户软删除
     * @param id
     * @return
     */
    @RequestMapping(value = "/deleteById",method = RequestMethod.POST)
    @ResponseBody
    public Object deleteById(@RequestParam("id") Long id){
        if(id == null){
            return renderError("id 不能为空",Result.OTHER);
        }
        //修改删除状态
        if(iSysUserService.deleteById(id)){
            return renderSuccess();
        }else{
            return renderError();
        }
    }


    /**
     * 唯一性验证
     * @param entity    实体参数
     */
    @RequestMapping(value = "/attrOnce", method = RequestMethod.POST)
    public @ResponseBody
    boolean attrOnce(SysUser entity) {
        return iSysUserService.selectByMapOnce(ObjectUtils.beanToMap(entity));
    }
}
